<template>
  <div class="app-main-container">
    <div class="df goods_sale_wrap">
      <div class="sell_left">
        <el-input
          ref="searchGoods"
          v-model="filters.goodsName"
          :placeholder="$t('message.qsr') + $t('message.spmctxm')"
          clearable
          @keyup.enter.native="codeEnter"
        >
          <el-button slot="append" icon="el-icon-search" @click="getList(1)" />
        </el-input>
        <div class="goods_tabs_wrap">
          <div class="list_wrap">
            <img
              class="btn btn_left"
              src="@/assets/images/ic_left.png"
              alt=""
              @click="moveTabs('left')"
            />
            <img
              class="btn btn_right"
              :class="{ shadow: tabsBtnShadow }"
              src="@/assets/images/ic_right.png"
              alt=""
              @click="moveTabs('right')"
            />
            <div id="scrollContent" class="list">
              <span class="empty" />
              <span
                v-for="item in typeList"
                :key="item.id"
                :class="{ active: item.name === selectType.name }"
                class="item"
                @click="goodsTabsClick(item)"
                >{{ item.name }}</span
              >
              <span class="empty" />
            </div>
          </div>
        </div>
        <div class="goods_wrap">
          <div class="good_content">
            <template v-for="(item, index) in goodsList">
              <div
                :key="index"
                class="card_style"
                :class="{ selected: item.isSelect }"
                @click="goodsItemClick(item, index)"
              >
                <img :src="item.picture" class="goods-image" alt="" />
                <div class="right-items">
                  <div class="goods-name">
                    {{
                      item.name.length > 8
                        ? item.name.slice(0, 6) + "..."
                        : item.name
                    }}
                  </div>
                  <div class="stock-style">
                    <span class="stock-title-style"
                      >{{ $t("message.kucun") }}：</span
                    >
                    <span class="stock-value-style">{{ item.stock }}</span>
                  </div>
                  <div class="add-module-style">
                    <div class="secondColor">
                      {{ $t("message.rmbfh") }}{{ item.price }}
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </div>
        </div>
        <Paginations
          :total="totalCount"
          :page-size="pagination.rows"
          :page="pagination.page"
          :integrated="integrated"
          @current-change="getList"
        />
      </div>
      <div class="sp" />
      <div class="goods_right">
        <div class="member_wrap">
          <div class="df">
            <MemberSearch
              ref="MemberSearchRef"
              class="flex1"
              @clear="memberClear"
              @select="memberSelect"
            />
            <el-button class="ml10" type="primary" @click="memberClear">{{
              $t("message.sk")
            }}</el-button>
          </div>
          <div class="df mt20 mb20">
            <span class="flex1"
              >{{ $t("message.name") }}：{{ memberInfo.nickName || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.sjh") }}：{{ memberInfo.phone || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.hydj") }}：{{ memberInfo.cardName || "-" }}</span
            >
            <span class="flex1"
              >{{ $t("message.czje") }}：{{
                memberInfo.rechargeMoney || "0.00"
              }}</span
            >
            <span class="flex1"
              >{{ $t("message.zsye") }}：{{
                memberInfo.giveMoney || "0.00"
              }}</span
            >
          </div>
        </div>
        <div class="table_wrap" style="width: 100%">
          <el-table
            ref="table"
            :data="saleGoodsList"
            element-loading-text="Loading"
            border
            fit
            height="96%"
            :header-row-class-name="'table-header'"
            class="doumee-element-table margin-t-20"
          >
            <el-table-column
              align="center"
              :label="$t('message.sp')"
              min-width="80"
              prop="name"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              :label="$t('message.dprice')"
              prop="price"
              show-overflow-tooltip
              min-width="40"
            />
            <el-table-column
              align="center"
              :label="$t('message.num')"
              width="126"
            >
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.buynum"
                  class="w100"
                  :min="1"
                  @change="selectTickNum(scope.row)"
                  :max="Number(scope.row.stock)"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" :label="$t('message.zhekou')" min-width="40" show-overflow-tooltip>
              <template slot-scope="scope">
                {{ '-' }}
              </template>
            </el-table-column> -->
            <el-table-column
              align="center"
              :label="$t('message.spzj')"
              min-width="60"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ (scope.row.buynum * scope.row.price).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('message.caozuo')"
              min-width="40"
              align="center"
              fixed="right"
            >
              <template slot-scope="scope">
                <div class="flex-cc">
                  <el-button
                    type="text"
                    class="secondColor"
                    @click="delSaleGoods(scope.$index)"
                    >{{ $t("message.del") }}</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-if="saleGoodsList.length" class="final_wrap">
          <div class="price_wrap">
            <div class="sum-style">
              <span class="sum-title">{{ $t("message.heji") }} ：</span>
              <span class="sum-value secondColor">{{ totalPrice() }}</span>
            </div>
          </div>
          <div class="sub_order">
            <el-input
              v-model="remark"
              :placeholder="$t('message.qsr') + $t('message.ddbz')"
            />
            <el-button
              v-preventReClick
              :loading="subLoading"
              class="ml20"
              type="primary"
              @click="settleAccount"
              >{{ $t("message.ddjs") }}
            </el-button>
            <el-button @click="clearOrder">{{ $t("message.clear") }}</el-button>
          </div>
        </div>
      </div>
    </div>
    <orderDialog
      ref="child"
      @openSuccess="subLoading = false"
      @orderSuccess="payOrderSuccess"
    />
  </div>
</template>

<script>
import { goodsClassifyListVenue, goodsListVenue, goodsDiscount } from "@/api";
import orderDialog from "@/components/order";
import MemberSearch from "@/components/MemberSearch";
export default {
  name: "GoodsSale",
  components: {
    orderDialog,
    MemberSearch,
  },
  data() {
    return {
      subLoading: false,
      activeTabs: {},
      tabsBtnShadow: true,
      memberInfo: {},
      remark: "",
      totalDistance: 0,
      transformX: 0,
      limitCount: 0,
      scrollWidth: 0,
      clientWidth: 0,
      meta: [],
      listLoading: true,
      activeType: "-1",
      discountInfo: "",
      selectType: {
        id: "-1",
      },
      integrated: false,
      typeList: [],
      goodsList: [],
      saleGoodsList: [],
      list: [],
      pagination: {
        page: 1,
        rows: 30,
      },
      totalCount: 0,
      swiperOptions: {
        slidesPerView: 4,
        slidesPerColumnFill: "row",
        slidesPerColumn: 4,
        observer: true, // 当改变swiper的样式（例如隐藏/显示）或者修改swiper的子元素时，自动初始化swiper
        observeParents: true, // 修改swiper的父元素时，自动初始化swiper
        pagination: {
          el: ".swiper-pagination-page",
        },
      },
      filters: {
        goodsName: "",
      },
    };
  },
  created() {
    this.meta = this.$route.meta.buttons || [];
    this.getClassifyList();
    this.getList(1);
  },
  mounted() {},
  activated() {
    this.$refs.table.doLayout();
    this.$refs.searchGoods.focus();
  },

  methods: {
    memberClear() {
      this.$refs.MemberSearchRef.clearSearch();
      this.memberInfo = {};
      this.androidSelectMember();
    },
    moveTabs(direction) {
      const scrollContent = document.querySelector("#scrollContent");
      if (this.limitCount === 0) {
        const scrollWidth = scrollContent.scrollWidth; // 一共可以滚动的宽度
        const clientWidth = scrollContent.clientWidth; // 本身占据的宽度

        this.scrollWidth = scrollWidth;
        this.clientWidth = clientWidth;
        this.totalDistance = scrollWidth - clientWidth;

        this.scrollWidth = scrollWidth;
        this.clientWidth = clientWidth;
      }
      if (this.totalDistance > 0 && direction === "right") {
        this.transformX = this.transformX - 450;
        scrollContent.style.transform = `translate(${this.transformX}px)`;
        this.totalDistance = this.totalDistance - 450;
      } else if (
        this.totalDistance < this.scrollWidth - this.clientWidth &&
        direction === "left"
      ) {
        this.transformX = this.transformX + 450;
        scrollContent.style.transform = `translate(${this.transformX}px)`;
        this.totalDistance = this.totalDistance + 450;
      }
      console.log(this.totalDistance);
      this.tabsBtnShadow = this.totalDistance > -40;
      this.limitCount += 1;
    },
    memberSelect(item) {
      this.memberInfo = item;
      this.androidSelectMember();
    },
    clearOrder() {
      if (window.Android) {
        let datas = [];
        let info = { datas };
        let obj = JSON.stringify(info);
        Android.setGoods(obj);
      }
      this.saleGoodsList = [];
      this.goodsList.forEach((item) => {
        item.isSelect = false;
      });
    },
    payOrderSuccess() {
      this.filters.goodsName = "";
      this.memberClear();
      this.clearOrder();
      this.codeEnter();

      //   this.$router.push({ name: 'OrderManager' })
    },
    // 场馆端商品分类列表
    getClassifyList() {
      goodsClassifyListVenue({
        param: {
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      })
        .then((res) => {
          if (res.errorCode !== "000000") return;
          this.typeList = [
            { name: this.$t("message.qb"), id: "-1" },
            ...res.recordList,
          ];
          this.selectType = this.typeList[0];
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    // 场馆端商品列表
    getList(page) {
      const { pagination } = this;
      if (page) pagination.page = page;
      goodsListVenue({
        pagination,
        param: {
          classifyId: this.selectType.id === "-1" ? "" : this.selectType.id,
          name: this.filters.goodsName,
          status: "1",
          type: 1,
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      })
        .then((res) => {
          if (res.errorCode !== "000000") return;
          this.goodsList = res.recordList;
          this.totalCount = res.totalCount;
          this.goodsList.forEach((item) => {
            item["buynum"] = 1;
            this.saleGoodsList.forEach((goods) => {
              if (goods.id === item.id) {
                item.isSelect = true;
              }
            });
          });
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    codeEnter() {
      this.pagination.page = 1;
      const { pagination } = this;
      goodsListVenue({
        pagination,
        param: {
          classifyId: this.selectType.id === "-1" ? "" : this.selectType.id,
          name: this.filters.goodsName,
          status: "1",
          type: 1,
          venueId: sessionStorage.getItem("venueId"),
          saleType: 0,
        },
      })
        .then((res) => {
          if (res.errorCode !== "000000") return;
          this.goodsList = res.recordList;
          this.totalCount = res.totalCount;
          this.goodsList.forEach((item) => {
            item["buynum"] = 1;
            this.saleGoodsList.forEach((goods) => {
              if (goods.id === item.id) {
                item.isSelect = true;
              }
            });
          });
          if (this.goodsList.length === 1) {
            const obj = JSON.parse(JSON.stringify(this.goodsList[0]));
            this.goodsItemClick(obj, 0);
            this.filters.goodsName = "";
          }
          this.listLoading = false;
        })
        .catch(() => {
          this.listLoading = false;
        });
    },
    toShow(scope) {
      // 展示折扣详情
      // list
      goodsDiscount({ param: { id: scope.row.id } }).then((res) => {
        if (res.errorCode !== "000000") return;
        const discountInfo = res.recordList;
        var memprice = "";
        discountInfo.forEach((item) => {
          memprice = memprice + item.cardName + ":" + item.memberPrice + " \n ";
        });
        this.discountInfo = memprice;
      });
    },
    goodsTabsClick(tab, event) {
      this.selectType = tab;
      this.pagination.page = 1;
      // this.selectType = this.typeList.find((item) => this.activeType === item.id)
      this.getList();
    },
    // 安卓选择会员
    androidSelectMember() {
      console.log(this.memberInfo, "===============4");
      let info = {
        showAvatar:
          this.memberInfo.showFaceUrl || this.memberInfo.showAvatar || "", //头像
        nickName: this.memberInfo.nickName || "", // //昵称
        phone: this.memberInfo.phone || "",
        integral: this.memberInfo.integral || "", // //积分
        totalMoney:
          (this.memberInfo.rechargeMoney + this.memberInfo.giveMoney).toFixed(
            2
          ) || 0, //总金额
      };
      console.log(info, "===============1");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setMember(obj);
        return;
      }
    },

    // 商品数量增加 减少
    selectTickNum(val) {
      console.log(val, "===============1");
      this.androidHandle();
    },
    // 安卓选择商品
    androidHandle() {
      let datas = [];
      this.saleGoodsList.forEach((item) => {
        datas.push({
          title: item.name,
          price: item.price,
          num: item.buynum,
          infos: [
            `${this.$t("message.dprice")}:${this.$t("message.rmbfh")}${
              item.price
            }`,
          ],
        });
      });
      let info = { datas };
      console.log(info, "===============3s");
      let obj = JSON.stringify(info);
      if (window.Android) {
        Android.setGoods(obj);
        return;
      }
    },
    goodsItemClick(item, index) {
      if (!item.stock || item.stock === "0") {
        return this.$message.info(this.$t("message.zsspkc"));
      }
      if (!item.isSelect) {
        const obj = JSON.parse(JSON.stringify(item));
        this.saleGoodsList.push(obj);
      } else {
        this.saleGoodsList = this.saleGoodsList.filter((goods) => {
          return item.id !== goods.id;
        });
      }
      const temp = [...this.goodsList];
      temp[index].isSelect = !temp[index].isSelect;
      this.goodsList = temp;
      this.androidHandle();
    },
    delSaleGoods(index) {
      this.goodsList.forEach((item) => {
        if (item.id === this.saleGoodsList[index].id) {
          item.isSelect = false;
        }
      });
      this.saleGoodsList.splice(index, 1);
      this.androidHandle();
    },
    totalPrice() {
      var totalPrice = 0;
      this.saleGoodsList.forEach((goods) => {
        totalPrice += goods.buynum * goods.price;
      });
      // for (const goods of this.saleGoodsList) {
      //   totalPrice += goods.buynum * goods.price
      // }
      return totalPrice.toFixed(2);
    },
    settleAccount() {
      // this.dialogTableVisible = true
      const { memberInfo, remark } = this;
      const goodsList = [];
      this.saleGoodsList.forEach((goods) => {
        goodsList.push({
          id: goods.id,
          goodsNum: goods.buynum,
        });
      });
      const config = { goodsList, memberId: memberInfo.id, remark };
      this.subLoading = true;
      this.$refs.child.continuePay(config, "goodsSale");
      setTimeout(() => {
        this.subLoading = false;
      }, 3000);
    },
    clear() {
      this.filters.goodsName = "";
      this.getList(1);
    },
  },
  beforeRouteLeave(to, from, next) {
    console.log(to, from, "to, from离开页面销毁订单");
    if (window.Android) {
      this.clearOrder();
      this.memberClear();
      Android.clearOrder();
    }
    next(); // 始终允许导航
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.app-main-container {
  height: calc(100% - 40px);
}
.goods_sale_wrap {
  height: 100%;
}
.sp {
  margin: 0 20px;
  width: 1px;
  height: 100%;
  background-color: #dfe2e8;
}
.sell_left {
  width: 560px;
  height: 100%;
  .goods_wrap {
    height: calc(100% - 160px);
    overflow: auto;
    .good_content {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
  }
}
.table_wrap {
  height: calc(100% - 200px);
}
.goods_right {
  flex: 1;
}
.goods_tabs_wrap {
  width: 100%;
  margin: 16px 0 20px;
  position: relative;
  overflow: hidden;
  .list_wrap {
    overflow-x: hidden;
    .list {
      display: flex;
      .empty {
        width: 40px;
        box-sizing: border-box;
        flex-shrink: 0;
      }
      .item {
        flex-shrink: 0;
        height: 35px;
        line-height: 35px;
        padding: 0 16px;
        background-color: #f5f7fc;
        border-radius: 2px;
        margin-right: 10px;
        cursor: pointer;
      }
      .active {
        background-color: $primaryColor;
        color: #fff;
      }
    }
  }

  .btn {
    height: 36px;
    width: 30px;
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
    z-index: 300;
    cursor: pointer;
  }
  .btn_left {
    left: 0;
  }
  .btn_right {
    right: 0;
  }
  .shadow {
    box-shadow: -2px -2px 4px 0px rgba(0, 0, 0, 0.08);
  }
}
.final_wrap {
  background: #f7f7f7;
  border-radius: 2px;
  padding: 20px;
  .price_wrap {
    display: flex;
    margin-bottom: 20px;
    .sum-style {
      font-size: 16px;
      margin-right: 75px;
      .sum-title {
        color: #222;
      }
      .sum-value {
        font-size: 17px;
        font-weight: 700;
      }
    }
  }
  .sub_order {
    display: flex;
  }
}

.card_style {
  width: calc(33.33% - 8px);
  height: 80px;
  border-radius: 2px;
  border: 1px solid #dfe2e8;
  box-sizing: border-box;
  display: flex;
  margin-right: 12px;
  margin-bottom: 10px;
  padding: 10px;
  cursor: pointer;
  &:nth-of-type(3n) {
    margin-right: 0;
  }
  img {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    padding: 0;
    border-radius: 2px;
  }
  .right-items {
    display: flex;
    flex-flow: column;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    .goods-name {
      color: #222;
      font-size: 14px;
      line-height: 14px;
    }
    .stock-style {
      font-size: 12px;
      line-height: 12px;
      .stock-title-style {
        color: #999;
      }
    }
  }
}
.selected {
  background: #f4f7fc;
  border-radius: 2px;
  border: 1px solid $primaryColor;
}
.bottom-style {
  height: 50px;
  border-left: 1px #dfe2e8 solid;
  border-right: 1px #dfe2e8 solid;
  border-bottom: 1px #dfe2e8 solid;
  .sum-style {
    margin-left: 10px;
    margin-top: 17px;
    height: 15px;
    float: left;
    .sum-title {
      color: #222;
      font-size: 13px;
    }
    .sum-value {
      color: #dd0707;
      font-size: 17px;
      font-weight: 700;
    }
  }
  .btn-style {
    float: right;
    width: 80px;
    height: 30px;
    margin-right: 10px;
    margin-top: 10px;
    background-color: #1943a9;
    color: #fff;
    text-align: center;
    border-radius: 4px;
    line-height: 30px;
    font-size: 13px;
    font-weight: 700;
  }
}
.count-style {
  margin-left: 5px;
  margin-right: 5px;
}
.pay-style {
  width: 110px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}

.settle-btn-style {
  margin-left: 20px;
}
.pre {
  white-space: pre;
  .discount-title {
    color: #303133;
    font-size: 16px;
    margin-bottom: 12px;
  }
}
</style>
